package com.njth.util;

import java.util.Date;
import java.util.Properties;
import java.text.*;
import javax.servlet.ServletContext;

import java.io.*;

public class Config implements Serializable{
	static final long serialVersionUID=20083271L;
	private static Config instance;
	private static String contentAbsolutPath;
	private static Properties configProperties;
	
	private static String configFilePath=null;
	
	private Config(ServletContext context){
		
		contentAbsolutPath=context.getRealPath("/");
		configFilePath=context.getInitParameter("com.njth.cofigFile");
		System.out.println("ContextPath:"+contentAbsolutPath);
		System.out.println("ConfigFile:"+configFilePath);
	
	}
	
	public static void createInstance(ServletContext context){
		if(instance==null)
			instance=new Config(context);
	}
	
	public static boolean hasCreated(){
		return instance!=null;
	}
	
	public static String getContenAbsolutPath(){
		return contentAbsolutPath;
	}
	
	public static String getConfigProperty(String key){
		if(configProperties==null){
			File configFile=null;
			if(configFilePath==null){
				configFile=new File(contentAbsolutPath+"WEB-INF/uploadConfig.properties");
			}else{
				configFile=new File(contentAbsolutPath+configFilePath);
			}
			configProperties=new Properties();
			try {
				configProperties.load(new FileInputStream(configFile));
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return configProperties.getProperty(key);
	}
	
	
	public static Date getClosingDate(){
		String dStr=getConfigProperty("closingDate");
		DateFormat df=DateFormat.getDateInstance();
		Date date=null;
		try {
			date=df.parse(dStr);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return date;
	}
}
